package com.dulehui.panku.rest;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.dulehui.panku.commons.entity.ResultObject;
import com.dulehui.panku.commons.utils.R;
import com.dulehui.panku.commons.utils.StringKit;
import com.dulehui.panku.dto.Darkxx;
import com.dulehui.panku.entity.BfQyhznr;
import com.dulehui.panku.entity.DaArchTid;
import com.dulehui.panku.entity.DaQyajb;
import com.dulehui.panku.entity.HzQyhznr;
import com.dulehui.panku.service.IDaQyajbService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * Created by Think on 2017/2/18 0018.
 */
@RestController
@RequestMapping("/api")
public class RestApiController {

    private static final int UNISCID_LENGTH = 36;
    @Autowired
    private IDaQyajbService iDaQyajbService;


    public static final Logger logger = LoggerFactory.getLogger(RestApiController.class);


    @RequestMapping("/test")
    public String test() {
        return "ok";
    }

    /**
     * 查询档案上架信息
     *
     * @param qyajTid
     * @param qyajEpc
     * @param cjbEpc
     * @return
     */
    @Deprecated
    @RequestMapping(value = "/qyajb/searchLocation", method = RequestMethod.GET)
    public Darkxx searchLocation(@RequestParam("qyaj_tid") String qyajTid,
                                 @RequestParam("qyaj_epc") String qyajEpc,
                                 @RequestParam("cjb_epc") String cjbEpc) {


        Darkxx darkxx = new Darkxx();

        HzQyhznr hzQyhznr = new HzQyhznr();

        DaArchTid daArchTid = new DaArchTid();
        daArchTid.setArchtid(qyajTid);
        daArchTid = daArchTid.selectById();
        if (daArchTid != null) {
            //找到了
            hzQyhznr.setNbxh(daArchTid.getNbxh());
            hzQyhznr = hzQyhznr.selectById();
            darkxx.setTid(qyajTid);
            darkxx.setNbxh(hzQyhznr.getNbxh());
            darkxx.setQymc(hzQyhznr.getQymc());
            darkxx.setZch(hzQyhznr.getZch());
            darkxx.setUniscid(hzQyhznr.getUniscid());

            String rkzt;
            if (cjbEpc.equals(daArchTid.getPripid())) {
                rkzt = "在架";
            } else {
                rkzt = "错架，" + "该档案已在" + convertCjbToMsg(daArchTid.getPripid()) + "上";
            }
            darkxx.setRkzt(rkzt);
        } else {

            String zch = null, uniscid = null;
            if (StringKit.epcHasChinese(qyajEpc)) {
                zch = StringKit.epcToChineseStr(qyajEpc);
            } else {
                //统一
                if (qyajEpc.length() == UNISCID_LENGTH) {
                    uniscid = StringKit.epcToString(qyajEpc);
                } else {
                    zch = StringKit.epcToString(qyajEpc);
                }
                hzQyhznr = new HzQyhznr();
                if (uniscid != null) {
                    hzQyhznr = hzQyhznr.selectOne(new EntityWrapper<HzQyhznr>().eq("uniscid", uniscid));
                } else {
                    hzQyhznr = hzQyhznr.selectOne(new EntityWrapper<HzQyhznr>().eq("zch", zch));
                }
                if (hzQyhznr != null) {
                    darkxx.setTid(qyajTid);
                    darkxx.setNbxh(hzQyhznr.getNbxh());
                    darkxx.setQymc(hzQyhznr.getQymc());
                    darkxx.setZch(hzQyhznr.getZch());
                    darkxx.setUniscid(hzQyhznr.getUniscid());
                    darkxx.setRkzt("未在架");
                } else {
                    //找不到该企业
                    darkxx.setTid(qyajTid);
                    darkxx.setRkzt("未找到该企业");
                }
            }

        }
        return darkxx;
    }

    /**
     * 查询档案上架信息
     *
     * @param qyajTid
     * @param qyajEpc
     * @return
     */
    @RequestMapping(value = "/qyajb/searchLocation2", method = RequestMethod.GET)
    public Darkxx searchLocation2(@RequestParam("qyaj_tid") String qyajTid,
                                  @RequestParam("qyaj_epc") String qyajEpc) {

        logger.debug("查询档案的上架信息,da_tid:{},da_epc:{}",qyajTid,qyajEpc);

        String transEpc = null;
        if (StringKit.epcHasChinese(qyajEpc)) {
            transEpc = StringKit.epcToChineseStr(qyajEpc);
        } else {
            //统一
            if (qyajEpc.length() == UNISCID_LENGTH) {
                transEpc = StringKit.epcToString(qyajEpc);
            } else {
                transEpc = StringKit.epcToString(qyajEpc);
            }
        }


        Darkxx darkxx = new Darkxx();
        darkxx.setTransEpc(transEpc);

        HzQyhznr hzQyhznr = new HzQyhznr();
        BfQyhznr bfQyhznr = new BfQyhznr();

        DaArchTid daArchTid = new DaArchTid();
        daArchTid.setArchtid(qyajTid);
        daArchTid = daArchTid.selectById();
        if (daArchTid != null) {
            logger.debug("DaArchTid表找到该条记录：{}",qyajTid);
            //找到了
            hzQyhznr.setNbxh(daArchTid.getNbxh());
            hzQyhznr = hzQyhznr.selectById();
            if(hzQyhznr!=null){
                logger.debug("查询库找到该条记录：{}",hzQyhznr.getNbxh());
                darkxx.setTid(qyajTid);
                darkxx.setNbxh(hzQyhznr.getNbxh());
                darkxx.setQymc(hzQyhznr.getQymc());
                darkxx.setZch(hzQyhznr.getZch());
                darkxx.setUniscid(hzQyhznr.getUniscid());
                darkxx.setCjh(daArchTid.getPripid());
                darkxx.setRkmsg("查询库");
            }else {
                logger.debug("备份库找到该条记录：{}",bfQyhznr.getNbxh());
                bfQyhznr = bfQyhznr.selectOne(new EntityWrapper<BfQyhznr>().eq("nbxh", daArchTid.getNbxh()));
                darkxx.setTid(qyajTid);
                darkxx.setNbxh(bfQyhznr.getNbxh());
                darkxx.setQymc(bfQyhznr.getQymc());
                darkxx.setZch(bfQyhznr.getZch());
                darkxx.setUniscid(bfQyhznr.getUniscid());
                darkxx.setCjh(daArchTid.getPripid());
                darkxx.setRkmsg("备份库");
            }
        } else {
            logger.debug("DaArchTid表未找到该条记录：{}",qyajTid);
            String zch = null, uniscid = null;
            if (StringKit.epcHasChinese(qyajEpc)) {
                zch = StringKit.epcToChineseStr(qyajEpc);
            } else {
                //统一
                if (qyajEpc.length() == UNISCID_LENGTH) {
                    uniscid = StringKit.epcToString(qyajEpc);
                } else {
                    zch = StringKit.epcToString(qyajEpc);
                }
            }
            hzQyhznr = new HzQyhznr();
            if (uniscid != null) {
                hzQyhznr = hzQyhznr.selectOne(new EntityWrapper<HzQyhznr>().eq("uniscid", uniscid));
            } else {
                hzQyhznr = hzQyhznr.selectOne(new EntityWrapper<HzQyhznr>().eq("zch", zch));
            }
            if (hzQyhznr != null) {
                logger.debug("查询库找到该条记录：{}",hzQyhznr.getNbxh());
                darkxx.setTid(qyajTid);
                darkxx.setNbxh(hzQyhznr.getNbxh());
                darkxx.setQymc(hzQyhznr.getQymc());
                darkxx.setZch(hzQyhznr.getZch());
                darkxx.setUniscid(hzQyhznr.getUniscid());
                darkxx.setRkmsg("查询库");
            } else {
                //去备份库查找

                bfQyhznr = new BfQyhznr();
                if (uniscid != null) {
                    bfQyhznr = bfQyhznr.selectOne(new EntityWrapper<BfQyhznr>().eq("uniscid", uniscid));
                } else {
                    bfQyhznr = bfQyhznr.selectOne(new EntityWrapper<BfQyhznr>().eq("zch", zch));
                }
                if (bfQyhznr!=null) {
                    logger.debug("备份库找到该条记录：{}",bfQyhznr.getNbxh());
                    darkxx.setTid(qyajTid);
                    darkxx.setNbxh(bfQyhznr.getNbxh());
                    darkxx.setQymc(bfQyhznr.getQymc());
                    darkxx.setZch(bfQyhznr.getZch());
                    darkxx.setUniscid(bfQyhznr.getUniscid());
                    darkxx.setRkmsg("备份库");
                }else {
                    //找不到该企业
                    logger.debug("未找到该企业：{}",qyajTid);
                    darkxx.setTid(qyajTid);
                }
            }
            //     }
        }
        return darkxx;
    }

    /**
     * 上架功能
     * 1.根据tid获取企业案卷信息
     * 2.2 如果企业案卷信息不存在，则读取qayjEpc信息，判断是统一社会信用代码还是注册号，找到该企业案卷信息，
     * 2.1 如果企业案卷信息存在，则更新posi_no信息为cjbEpc
     * 2.3 更新到关系表中
     *
     * @param qyajTid
     * @param qyajEpc
     * @param cjbEpc
     * @return
     */
    @RequestMapping(value = "/qyajb/bindEpc", method = RequestMethod.POST)
    public R bindEpc(@RequestParam("qyaj_tid") String qyajTid,
                     @RequestParam("qyaj_epc") String qyajEpc,
                     @RequestParam("cjb_epc") String cjbEpc) {

        logger.debug("档案上架,da_tid:{},da_epc:{},cjh_epc：{}",qyajTid,qyajEpc,cjbEpc);
        //DaQyajb daQyajb = new DaQyajb();

        DaArchTid daArchTid = new DaArchTid();
        daArchTid.setArchtid(qyajTid);
        daArchTid = daArchTid.selectById();
        if (daArchTid != null) {
            if (cjbEpc.equals(daArchTid.getPripid())) {
                //"在架";
                return R.error("该档案已在当前架上");
            } else {
                //"错架";
                return R.error("该档案已在" + convertCjbToMsg(daArchTid.getPripid()) + "上");
            }
        }
        String zch = null, uniscid = null;
        if (StringKit.epcHasChinese(qyajEpc)) {
            zch = StringKit.epcToChineseStr(qyajEpc);
        } else {
            if (qyajEpc.length() == UNISCID_LENGTH) {
                uniscid = StringKit.epcToString(qyajEpc);
            } else {
                zch = StringKit.epcToString(qyajEpc);
            }
        }
        HzQyhznr hzQyhznr = new HzQyhznr();
        if (uniscid != null) {
            hzQyhznr = hzQyhznr.selectOne(new EntityWrapper<HzQyhznr>().eq("uniscid", uniscid));
        } else {
            hzQyhznr = hzQyhznr.selectOne(new EntityWrapper<HzQyhznr>().eq("zch", zch));
        }
        if (hzQyhznr != null) {
            daArchTid = new DaArchTid();
            daArchTid.setNbxh(hzQyhznr.getNbxh());
            daArchTid.setArchtid(qyajTid);
            daArchTid.setPripid(cjbEpc);
            daArchTid.insert();
            return R.ok("上架成功");
        } else {
//                //找不到该企业
            BfQyhznr bfQyhznr = new BfQyhznr();
            if (uniscid != null) {
                bfQyhznr = bfQyhznr.selectOne(new EntityWrapper<BfQyhznr>().eq("uniscid", uniscid));
            } else {
                bfQyhznr = bfQyhznr.selectOne(new EntityWrapper<BfQyhznr>().eq("zch", zch));
            }
            if (bfQyhznr!=null) {
                daArchTid = new DaArchTid();
                daArchTid.setNbxh(bfQyhznr.getNbxh());
                daArchTid.setArchtid(qyajTid);
                daArchTid.setPripid(cjbEpc);
                daArchTid.insert();
                return R.ok("上架成功");
            }else {
                //找不到该企业
                return R.error("该企业未找到");
            }
        }
    }

    /**
     * 下架
     *
     * @param qyajTid
     * @param cjbEpc
     * @return
     */
    @RequestMapping(value = "/qyajb/unbindEpc", method = RequestMethod.POST)
    public R unbindEpc(@RequestParam("qyaj_tid") String qyajTid,
                       @RequestParam(value = "cjb_epc", required=false) String cjbEpc) {
        logger.debug("档案下架,da_tid:{},cjh_epc：{}",qyajTid,cjbEpc);
        DaArchTid daArchTid = new DaArchTid();
        daArchTid.setArchtid(qyajTid);
        daArchTid = daArchTid.selectById();
        if(daArchTid==null){
            return R.ok("该企业未找到或已下架");
        }
        //if (daArchTid.getArchtid() != null) {
            //20171021  不再判断，直接下架先
//            if (cjbEpc.equals(daArchTid.getPripid())) {
//                //"在架";
//                daArchTid.deleteById();
//                return R.ok("下架成功");
//            } else {
//                //"错架";
//                return R.error("该档案已在" + convertCjbToMsg(daArchTid.getPripid()) + "上，无法下架");
//            }
            daArchTid.deleteById();
            return R.ok("下架成功");
        //} else {
        //    return R.ok("该企业未找到或已下架");
        //}

    }

    @RequestMapping(value = "/searchByCjb", method = RequestMethod.GET)
    public List<Map<String, Object>> findTids(@RequestParam(value = "cjb_epc") String cjbEpc) {
        logger.debug("根据层架号搜索,cjh_epc：{}",cjbEpc);
        List<Map<String, Object>> tidList = Lists.newArrayList();

        HzQyhznr hzQyhznr = new HzQyhznr();
        BfQyhznr bfQyhznr = new BfQyhznr();
        DaArchTid daArchTid = new DaArchTid();
        List<DaArchTid> ajList2 = daArchTid.selectList(new EntityWrapper<DaArchTid>().eq("pripid", cjbEpc));
        for (int i = 0; i < ajList2.size(); i++) {
            DaArchTid archTid = ajList2.get(i);
            Map<String, Object> map = Maps.newHashMap();
            map.put("nbxh", archTid.getNbxh());
            map.put("tid", archTid.getArchtid());
            hzQyhznr = new HzQyhznr();
            hzQyhznr = hzQyhznr.selectById(archTid.getNbxh());
            if(hzQyhznr!=null){
                map.put("qymc", hzQyhznr.getQymc());
                map.put("zch", hzQyhznr.getZch());
                map.put("uniscid", hzQyhznr.getUniscid());
                map.put("cjh", cjbEpc);
                map.put("rkzt", "正常");
                tidList.add(map);
            }else{
                bfQyhznr = new BfQyhznr();
                bfQyhznr = bfQyhznr.selectOne(new EntityWrapper<BfQyhznr>().eq("nbxh", archTid.getNbxh()));
                if(bfQyhznr!=null){
                    map.put("qymc", bfQyhznr.getQymc());
                    map.put("zch", bfQyhznr.getZch());
                    map.put("uniscid", bfQyhznr.getUniscid());
                    map.put("cjh", cjbEpc);
                    map.put("rkzt", "正常");
                    tidList.add(map);
                }
            }

        }
        return tidList;
    }

    public String convertCjbToMsg(String cjbEpc) {
        //A00000000001020700200504
        if (StringUtils.isEmpty(cjbEpc) || cjbEpc.length() != 24) {
            return cjbEpc+"(该层架号不符合规范)";
        }
        if (!cjbEpc.startsWith("A0000000000102")) {
            return cjbEpc+"(该层架号不符合规范)";
        }
        StringBuilder sb = new StringBuilder();
        String jh = cjbEpc.substring(14, 16);
        String hh = cjbEpc.substring(16, 19);
        String lh = cjbEpc.substring(19, 22);
        String ch = cjbEpc.substring(22, 24);

        sb.append(jh).append("架 ").append(hh).append("行 ").append(lh).append("列 ").append(ch).append("层");
        return sb.toString();
    }

}
